package com.google.demo.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.google.demo.R;
import com.google.demo.ScanQRCodeApp;
import com.google.demo.interfaces.AlertDialogInterface;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Debug;
import android.provider.Settings.Secure;
import android.support.v4.util.LruCache;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Util {
	public static String hashString(String string) {
		String hashword = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(string.getBytes());
			BigInteger hash = new BigInteger(1, md5.digest());
			hashword = hash.toString(16);
		} catch (NoSuchAlgorithmException nsae) {
		}
		return hashword;
	}

	public static String formatDurationFromMs(long duration, boolean padding) {
		duration = duration / 1000;
		long hh = duration / 3600;
		long mm = (duration % 3600) / 60;
		long ss = duration % 60;
		String text = "";
		if (padding) {
			if (hh > 0) {
				text = String.format("%02d:%02d:%02d", hh, mm, ss);
			} else {
				text = String.format("%02d:%02d", mm, ss);
			}
		} else {
			if (hh > 0) {
				text = String.format("%d:%d:%02d", hh, mm, ss);
			} else {
				text = String.format("%d:%02d", mm, ss);
			}
		}
		return text;
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_4444);
		Canvas canvas = new Canvas(output);

		final int color = 0xffffffff;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

		canvas.drawBitmap(bitmap, rect, rect, paint);
		bitmap.recycle();
		return output;
	}

	static Paint SHADOW_PAINT;
	final static float SHADOW_RADIUS = 8.5f;
	final static int SHADOW_COLOR = 0xEE000000;
	final static double SHADOW_RATIO = 0.07;

	public static Bitmap createShadow(Bitmap source, float roudedRadius) {
		SHADOW_PAINT = new Paint();
		SHADOW_PAINT
				.setShadowLayer(SHADOW_RADIUS / 2, 0.0f, 0.0f, SHADOW_COLOR);
		SHADOW_PAINT.setAntiAlias(true);
		SHADOW_PAINT.setFilterBitmap(true);
		SHADOW_PAINT.setColor(0xFF000000);
		SHADOW_PAINT.setStyle(Paint.Style.FILL);

		if (source == null)
			return null;

		final float bitmapWidth = (float) source.getWidth();
		final float bitmapHeight = (float) source.getHeight();

		final Canvas canvas = new Canvas();

		int extraW = (int) (source.getWidth() * SHADOW_RATIO);
		int extraH = (int) (source.getHeight() * SHADOW_RATIO);
		Bitmap bitmap;
		try {
			bitmap = Bitmap.createBitmap(source.getWidth() + extraW,
					source.getHeight() + extraH, Bitmap.Config.ARGB_4444);
			canvas.setBitmap(bitmap);

		} catch (OutOfMemoryError e) {
			return source;
		}
		final RectF to = new RectF(0, 0, bitmapWidth, bitmapHeight);
		final RectF to2 = new RectF(extraW, extraH, bitmapWidth, bitmapHeight);
		if (roudedRadius != 0)
			canvas.drawRoundRect(to2, roudedRadius, roudedRadius, SHADOW_PAINT);
		else
			canvas.drawRect(to2, SHADOW_PAINT);

		canvas.drawBitmap(source, null, to, null);
		source.recycle();
		return bitmap;
	}

	public static Bitmap createBorder(Bitmap source, int borderSize) {
		SHADOW_PAINT = new Paint();
		SHADOW_PAINT.setAntiAlias(true);
		SHADOW_PAINT.setColor(0xFFFFFFFF);
		SHADOW_PAINT.setStyle(Paint.Style.FILL);

		if (source == null)
			return null;
		Bitmap bitmap;
		final Canvas canvas = new Canvas();
		try {
			bitmap = Bitmap.createBitmap(source.getWidth() + borderSize,
					source.getHeight() + borderSize, Bitmap.Config.ARGB_4444);
			canvas.setBitmap(bitmap);
		} catch (OutOfMemoryError e) {
			return source;
		}
		canvas.drawRect(0, 0, source.getWidth() + borderSize,
				source.getHeight() + borderSize, SHADOW_PAINT);
		canvas.drawBitmap(source, borderSize / 2, borderSize / 2, SHADOW_PAINT);
		return bitmap;
	}

	public static String convertDateToString(Date date) {
		DateFormat myDateFormat = DateFormat.getDateInstance(DateFormat.FULL);
		return myDateFormat.format(date);
	}

	public static Date convertStringToDate(String dateStr) {
		DateFormat myDateFormat = DateFormat.getDateInstance(DateFormat.FULL);
		try {
			return myDateFormat.parse(dateStr);
		} catch (ParseException e) {
			return null;
		}
	}

	private static final int IO_BUFFER_SIZE = 4 * 1024;

	public static void copyStream(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[IO_BUFFER_SIZE];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

	private static final String KEY_STRING = "GNT-VNAM";

	public static byte[] encrypt(byte[] raw) {
		if (raw == null) {
			return null;
		}
		try {
			// Generate the secret key specs.
			Key key = new SecretKeySpec(KEY_STRING.getBytes(), "DES");
			// Generate the secret key specs.
			Cipher cipher = Cipher.getInstance("DES");

			cipher.init(Cipher.ENCRYPT_MODE, key);

			byte[] encrypted = cipher.doFinal(raw);
			return encrypted;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] decrypt(byte[] encrypt) {
		if (encrypt == null) {
			return null;
		}
		try {
			// Generate the secret key specs.
			Key key = new SecretKeySpec(KEY_STRING.getBytes(), "DES");
			// Generate the secret key specs.
			Cipher cipher = Cipher.getInstance("DES");

			cipher.init(Cipher.DECRYPT_MODE, key);

			byte[] decrypted = cipher.doFinal(encrypt);
			return decrypted;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	 /*
     * HACKISH: These constants aren't yet available in my API level (7), but I need to handle these cases if they come up, on newer versions
     */
    public static final int NETWORK_TYPE_EHRPD=14; // Level 11
    public static final int NETWORK_TYPE_EVDO_B=12; // Level 9
    public static final int NETWORK_TYPE_HSPAP=15; // Level 13
    public static final int NETWORK_TYPE_IDEN=11; // Level 8
    public static final int NETWORK_TYPE_LTE=13; // Level 11
    
	public static boolean isNetworkAvailable() {
		ScanQRCodeApp mobionApp = ScanQRCodeApp.Instance();
		ConnectivityManager connMgr = (ConnectivityManager) mobionApp
				.getApplicationContext().getSystemService(
						Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();
	     return (info != null && info.isConnected()); //&& Util.isConnectionFast(info.getType(),info.getSubtype()));
	    }

	    /**
	     * Check if the connection is fast
	     * @param type
	     * @param subType
	     * @return
	     */
	    public static boolean isConnectionFast(int type, int subType){
	        if(type==ConnectivityManager.TYPE_WIFI){
	            return true;
	        }else if(type==ConnectivityManager.TYPE_MOBILE){
	            switch(subType){
	            case TelephonyManager.NETWORK_TYPE_1xRTT:
	                return false; // ~ 50-100 kbps
	            case TelephonyManager.NETWORK_TYPE_CDMA:
	                return false; // ~ 14-64 kbps //2G or CDMA
	            case TelephonyManager.NETWORK_TYPE_EDGE:
	                return false; // ~ 50-100 kbps //2G or GSM
	            case TelephonyManager.NETWORK_TYPE_EVDO_0:
	                return true; // ~ 400-1000 kbps
	            case TelephonyManager.NETWORK_TYPE_EVDO_A:
	                return true; // ~ 600-1400 kbps
	            case TelephonyManager.NETWORK_TYPE_GPRS:
	                return false; // ~ 100 kbps
	            case TelephonyManager.NETWORK_TYPE_HSDPA:
	                return true; // ~ 2-14 Mbps
	            case TelephonyManager.NETWORK_TYPE_HSPA:
	                return true; // ~ 700-1700 kbps
	            case TelephonyManager.NETWORK_TYPE_HSUPA:
	                return true; // ~ 1-23 Mbps
	            case TelephonyManager.NETWORK_TYPE_UMTS:
	                return true; // ~ 400-7000 kbps //3G
	            // NOT AVAILABLE YET IN API LEVEL 7
	            case Util.NETWORK_TYPE_EHRPD:
	                return true; // ~ 1-2 Mbps
	            case Util.NETWORK_TYPE_EVDO_B:
	                return true; // ~ 5 Mbps
	            case Util.NETWORK_TYPE_HSPAP:
	                return true; // ~ 10-20 Mbps
	            case Util.NETWORK_TYPE_IDEN:
	                return false; // ~25 kbps 
	            case Util.NETWORK_TYPE_LTE:
	                return true; // ~ 10+ Mbps
	            // Unknown
	            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
	                return false; 
	            default:
	                return false;
	            }
	        }else{
	            return false;
	        }
	    }
	public static void showError(Context context, String Title, String Message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(Title);
		builder.setMessage(Message);
		final AlertDialog alertError = builder.create();
		alertError.setButton(context.getString(R.string.OK), new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				alertError.dismiss();
			}
		});
		builder.create();
		alertError.show();
	}

	public static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the Reader.read(char[]
		 * buffer) method. We iterate until the Reader return -1 which means
		 * there's no more data to read. We use the StringWriter class to
		 * produce the string.
		 */

		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} catch (IOException e) {
				return "";
			} finally {
				try {
					is.close();
				} catch (IOException e) {

				}
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	public static Bitmap resize_to_fit_in(Bitmap image, int sizeHeight,
			int sizeWidth) {
		int w = image.getWidth();
		int h = image.getHeight();
		// Calculate the scale factor
		float sW = ((float) sizeWidth) / w;
		float sH = ((float) sizeHeight) / h;
		// do NOT fsck with the aspect ratio: make sure we scale at 1:1
		if (sW > sH)
			sW = sH;
		else
			sH = sW;
		// scale the image by the calculated scale factor
		Matrix matrix = new Matrix();
		matrix.postScale(sW, sH);
		Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, w, h, matrix,
				true);
		return resizedBitmap;
	}

	public static Bitmap resizeBimap(Bitmap bitmap, int newWidth, int newHeight) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return resizeBitmap;
	}

	public static Bitmap cropBitmap(Bitmap bitmap, int newWidth, int newHeight) {
		Bitmap scaleBitmap;
		if (bitmap.getHeight() > bitmap.getWidth())
			scaleBitmap = Bitmap.createScaledBitmap(bitmap, newWidth,
					bitmap.getHeight() * newWidth / bitmap.getWidth(), true);
		else
			scaleBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth()
					* newHeight / bitmap.getHeight(), newHeight, true);
		Bitmap cropedBitmap = Bitmap.createBitmap(scaleBitmap, 0, 0, newWidth,
				newHeight);
		scaleBitmap.recycle();
		return cropedBitmap;
	}

	public static boolean isEmail(String email) {
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	public static int clearCacheFolder(final File dir, final int numDays) {

		int deletedFiles = 0;
		if (dir != null && dir.isDirectory()) {
			try {
				for (File child : dir.listFiles()) {

					// first delete subdirectories recursively
					if (child.isDirectory()) {
						deletedFiles += clearCacheFolder(child, numDays);
					}
					// then delete the files and subdirectories in this dir
					// only empty directories can be deleted, so subdirs have
					// been done first
					if (child.lastModified() < new Date().getTime() - numDays
							* DateUtils.DAY_IN_MILLIS) {
						if (child.delete()) {
							deletedFiles++;
						}
					}
				}
			} catch (Exception e) {
				Log.e("Util",
						String.format("Failed to clean the cache, error %s",
								e.getMessage()));
			}
		}
		return deletedFiles;
	}

	public static void clearCache(final Context context, final int numDays) {
		Log.i("Util", String.format(
				"Starting cache prune, deleting files older than %d days",
				numDays));
		int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
		Log.i("Util", String.format(
				"Cache pruning completed, %d files deleted", numDeletedFiles));
	}

	public static boolean checkSimCardState(Context context) {
		TelephonyManager telMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		int simState = telMgr.getSimState();
		boolean isSim=false;
		switch (simState) {
		case TelephonyManager.SIM_STATE_ABSENT:
			
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_PIN_REQUIRED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_PUK_REQUIRED:
			isSim=false;
			break;
		case TelephonyManager.SIM_STATE_READY:
			isSim=true;
			break;
		case TelephonyManager.SIM_STATE_UNKNOWN:
			isSim=false;
			break;
		}
		return isSim;
		
	}

	public static String getNowTime(Context context) {
		String result = "";
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("MMM dd,yyyy HH:mm:ssaa");
		result = df.format(c.getTime());
		return result;
	}

	public static String getNowTimeMillis(Context context) {
		String result = "";
		Calendar c = Calendar.getInstance();
		result = c.getTimeInMillis() + "";
		return result;
	}

	public static boolean isStringEmpty(String s) {
		if (s == null)
			return true;
		if (s.equals(""))
			return true;
		return false;
	}
	public static final String getUserAgentString(Context context) {
		try {
			Constructor<WebSettings> constructor = WebSettings.class
					.getDeclaredConstructor(Context.class, WebView.class);
			constructor.setAccessible(true);
			try {
				WebSettings settings = constructor.newInstance(context, null);
				return settings.getUserAgentString();
				
			} finally {
				constructor.setAccessible(false);
			}
		} catch (Exception e) {
			return new WebView(context).getSettings().getUserAgentString();
		}
	}
	public static void setFont(TextView view,Context context,String fontname){
		Typeface font1 = Typeface.createFromAsset(context.getAssets(), fontname);
        view.setTypeface(font1);
	}
	public static String getFormatDistance(double input, int num)
	{
		String output = "" + input;
		if(num > 0)
			num = num + 1;
		int i = 0;
		for(i = 0; i < output.length(); i++)
		{
			String sub = output.substring(i, i + 1);
			if(sub.equalsIgnoreCase("."))
			{
				i = i + num;
				break;
			}
		}
		while(i > output.length())
		{
			output = output + "0";
		}
			
		if(i > 0)
			return output.substring(0, i);
		else
			return "0";
	}
	private static class DownloadImage extends AsyncTask<Void, Void, Bitmap> {
		private String mUrl;
		private ImageView mImageView;
		private ProgressBar mProgressBar;
		private Context mContext;
		private boolean isResize=false;
		private boolean isBorder=false;
		private LruCache<String, Bitmap> mMemoryCache;
		public DownloadImage(Context context,boolean isResize,boolean isBorder,String url, ImageView imgView,ProgressBar progressBar,
				LruCache<String, Bitmap> mMemoryCache) {
			this.mUrl = url;
			this.mImageView = imgView;
			this.mProgressBar=progressBar;
			this.mContext=context;
			this.isResize=isResize;
			this.isBorder=isBorder;
			this.mMemoryCache=mMemoryCache;
		}
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if(mProgressBar!=null)
				mProgressBar.setVisibility(View.VISIBLE);
		}
		@Override
		protected Bitmap doInBackground(Void... params) {
			Bitmap bmp = null;
			HttpURLConnection conn = null;
			InputStream is = null;
			try {
				URL urln = new URL(mUrl);
				conn = (HttpURLConnection) urln.openConnection();
				is = conn.getInputStream();
				bmp = BitmapFactory.decodeStream(is);
			} catch (OutOfMemoryError e) {
				Log.e("Util OutOfMemoryError", "doInBackground "  + e.toString());
				try {
					if (conn != null)
						conn.disconnect();
					if (is != null)
						is.close();
				} catch (Exception ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				}
				return null;
			} catch (Exception e) {
				try {
					if (conn != null)
						conn.disconnect();
					if (is != null)
						is.close();
				} catch (Exception ex) {
					// TODO Auto-generated catch block
					ex.printStackTrace();
				}
				return null;
			}
			return bmp;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				String _id = Util.hashString(mUrl);
				if(mMemoryCache!=null){
					synchronized (mMemoryCache) {
						addBitmapToMemoryCache(_id, result, mMemoryCache);
					}
				}
				
				try {
					String dir = mContext.getCacheDir() + "/" + _id + "_mp.jpg";
					FileOutputStream out = new FileOutputStream(dir);
					result.compress(Bitmap.CompressFormat.JPEG, 80, out);
					if(isBorder){
						result=Util.createBorder(result, 10);
					}
					if(isResize){
						result=Util.resizeBimap(result, 100, 100);
					}
					
					out.flush();
					out.close();
					mImageView.setImageBitmap(result);
					if(mProgressBar!=null)
					mProgressBar.setVisibility(View.GONE);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}

	}
	
	public static void addBitmapToMemoryCache(String key, Bitmap bitmap, LruCache<String, Bitmap> mMemoryCache) {
	    if (mMemoryCache != null && getBitmapFromMemCache(key, mMemoryCache) == null) {
	    	try {
	    		mMemoryCache.put(key, bitmap);
	    	} catch(OutOfMemoryError e) {
	    		e.printStackTrace();
	    		System.gc();
	    	}
	    }
	}
	
	public static Bitmap getBitmapFromMemCache(String key, LruCache<String, Bitmap> mMemoryCache) {
		if(mMemoryCache != null) {
			return mMemoryCache.get(key);
		} else {
			return null;
		}
	}
	
	public static void download(Context mContext,boolean isResize,boolean isBorder,String url, ImageView imgv,ProgressBar progressBar,int defaultResID,
			LruCache<String, Bitmap> mMemoryCache) {
		if (url != null) {
			String _id = Util.hashString(url);
			Bitmap bitmap = getBitmapFromMemCache(_id, mMemoryCache);
			if(bitmap != null)
			{
				imgv.setImageBitmap(bitmap);
				return;
			}
			String dir;
			dir = mContext.getCacheDir() + "/" + _id + "_mp.jpg";
			File file = new File(dir);
			if (file.exists()) {
				FileInputStream fis = null;
				try {				
					fis = new FileInputStream(file);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inTempStorage = new byte[16 * 1024];
					Bitmap covertArt = BitmapFactory.decodeStream(fis,null,options);
					if(isResize){
						covertArt=Util.resizeBimap(covertArt, 100, 100);
					}
					if(isBorder){
						covertArt=Util.createBorder(covertArt, 10);
					}
					imgv.setImageBitmap(covertArt);
					addBitmapToMemoryCache(_id, covertArt, mMemoryCache);
				} catch(OutOfMemoryError e) {
					System.gc();
					imgv.setImageResource(defaultResID);
				}
				
			} else {
				new DownloadImage(mContext,isResize,isBorder,url, imgv,progressBar,mMemoryCache).execute();
			}
		}
	}
	public static void download(Context mContext,boolean isResize,boolean isBorder,String url, ImageView imgv,ProgressBar progressBar) {
		if (url != null) {
			
			String _id = Util.hashString(url);
			String dir;
			dir = mContext.getCacheDir() + "/" + _id + "_mp.jpg";
			File file = new File(dir);
			if (file.exists()) {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inTempStorage = new byte[16 * 1024];
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(file);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					Bitmap covertArt = BitmapFactory.decodeStream(fis,null,options);
					imgv.setImageBitmap(covertArt);
				} catch(OutOfMemoryError e) {
					Log.e("Util OutOfMemoryError", "download " + e.toString());
					imgv.setImageResource(R.drawable.ic_launcher);
			        System.gc();
				}
				
			} else {
				new DownloadImage(mContext,isResize,isBorder,url, imgv,progressBar,null).execute();
			}
		}
	}
	
	
	public static boolean checkBitmapFitsInMemory(long bmpwidth,long bmpheight, int bmpdensity ){
	    long reqsize=bmpwidth*bmpheight*bmpdensity;
	    long allocNativeHeap = Debug.getNativeHeapAllocatedSize();


	    final long heapPad=(long) Math.max(4*1024*1024,Runtime.getRuntime().maxMemory()*0.1);
	    if ((reqsize + allocNativeHeap + heapPad) >= Runtime.getRuntime().maxMemory())
	    {
	        return false;
	    }
	    return true;

	}
	public static final void clearCookieWeb(Context context){
		CookieSyncManager cookieSyncMngr = CookieSyncManager
				.createInstance(context);
		cookieSyncMngr.stopSync();
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
	}
	
	public static void showAlertDialog(final Activity activity,final AlertDialogInterface callback,boolean optionNo,boolean optionYes,String title,String message,String yes,String no){
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setTitle(title);
		builder.setMessage(message);
		builder .setCancelable(false);
		if(optionNo){
			builder.setNegativeButton(no, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               dialog.cancel();
		               callback.onChooseNoCallback();
		           }
		       });
		}
		if(optionYes){
			builder.setPositiveButton(yes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                callback.onChooseYesCallback();
		           }
		       });
		}
		
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public static final String  getAndroidID(Context context){
		return Secure.getString(context
				.getContentResolver(), Secure.ANDROID_ID);
	}
	
	public static void showMessage(Context context,String message,int length){
		Toast.makeText(context, message, length).show();
	}
	
}
